package com.yang.semaphore;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.Random;

/**
 * 停车场示例 - 信号量控制资源访问
 * 模拟停车场有限车位的场景
 */
public class ParkingLotExample {

    // 停车场总共有8个车位
    private static final int TOTAL_PARKING_SPOTS = 8;
    private static final Semaphore parkingSemaphore = new Semaphore(TOTAL_PARKING_SPOTS);

    // 记录当前可用车位数
    private static int availableSpots = TOTAL_PARKING_SPOTS;

    public static void main(String[] args) {
        System.out.println("=== 智能停车场系统启动 ===");
        System.out.println("总车位数: " + TOTAL_PARKING_SPOTS);
        System.out.println("当前可用车位: " + availableSpots);
        System.out.println("========================");

        // 创建15辆车尝试停车
        for (int i = 1; i <= 15; i++) {
            Thread car = new Thread(new Car("车辆-" + String.format("%02d", i)));
            car.start();

            // 稍微错开车辆到达时间
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }

    static class Car implements Runnable {
        private final String carId;
        private final Random random = new Random();

        public Car(String carId) {
            this.carId = carId;
        }

        @Override
        public void run() {
            try {
                System.out.println(carId + " 到达停车场，寻找车位...");

                // 尝试获取停车位，最多等待5秒
                if (parkingSemaphore.tryAcquire(5, TimeUnit.SECONDS)) {
                    // 成功获取车位
                    synchronized (ParkingLotExample.class) {
                        availableSpots--;
                        System.out.println("✅ " + carId + " 成功停车！剩余车位: " + availableSpots);
                    }

                    // 模拟停车时间（3-8秒）
                    int parkingTime = 3000 + random.nextInt(5000);
                    System.out.println("🚗 " + carId + " 停车中，预计停留时间: " + parkingTime / 1000 + "秒");
                    Thread.sleep(parkingTime);

                    // 离开停车场
                    System.out.println("🚙 " + carId + " 准备离开停车场");

                } else {
                    // 等待超时，没有获取到车位
                    System.out.println("❌ " + carId + " 等待超时，停车场已满，离开寻找其他停车场");
                    return;
                }

            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.out.println("⚠️ " + carId + " 停车过程被中断");
            } finally {
                // 检查是否需要释放车位（通过检查当前线程是否持有许可）
                if (parkingSemaphore.availablePermits() < TOTAL_PARKING_SPOTS) {
                    synchronized (ParkingLotExample.class) {
                        availableSpots++;
                        System.out.println("🔓 " + carId + " 离开停车场，释放车位。当前可用车位: " + availableSpots);
                    }
                    parkingSemaphore.release();
                }
            }
        }
    }
}
